package com.baidu.cmsWeb.contorllers;

import com.baidu.cmsCommes.pojo.Role;
import com.baidu.cmsCommes.util.PageUtil;
import com.baidu.cmsService.services.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * @Author: BSS
 * @create: 2020/6/22/19:51
 */
@Controller
@RequestMapping
public class RoleContorller {
    @Autowired
    private RoleService roleService;

    @GetMapping("/admin/role/roles")
    public String RoleIndex(Model model){
        PageUtil.initPage();
        List<Role> roleList = roleService.roleList();
        model.addAttribute("roles",roleList);
        return "role/list";
    }

    @GetMapping("/admin/role/add")
    public String toSave(Model model){
        List<String> types = roleService.getAllType();

        model.addAttribute("types",types).addAttribute("role",new Role());

        return "role/add";
    }

    @PostMapping("/admin/role/add")
    public String saveRole(Role role){
        Boolean flag =  roleService.saveRole(role);

        if (!flag)
            return "error";

        return "redirect:/admin/role/roles";
    }

    @GetMapping("/admin/role/delete/{rid}")
    public String deleteRole(@PathVariable("rid")Integer rid){
        Boolean flag = roleService.deleteRole(rid);

        if (!flag)
            return "error";

        return "redirect:/admin/role/roles";
    }

    @GetMapping("/admin/role/update/{rid}")
    public String toUpdate(@PathVariable("rid")Integer rid,Model model){
        Role role = roleService.selectById(rid);
        List<String> list = roleService.getAllType();

        if (role==null)
            return "error";

        model.addAttribute("role",role).addAttribute("types",list);

        return "role/update";
    }

    @PostMapping("/admin/role/update/{rid}")
    public String updateRole(@PathVariable("rid")Integer rid,Role role){
        Boolean flag = roleService.updateRole(role);
        if (!flag)
            return "error";

        return "redirect:/admin/role/roles";
    }

    @GetMapping("/admin/role/clearUsers/{rid}")
    public String clearUsers(@PathVariable("rid")Integer rid){
        Boolean flag = roleService.deleteUserRole(rid);

        if (!flag)
            return "error";

        return "redirect:/admin/role/roles";
    }
}
